﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.Controls
{
    /// <summary>
    /// 虚拟化列表控件（支持大数据量显示）
    /// </summary>
    public class VirtualListView : ListView
    {
        private const int DefaultItemHeight = 24;
        private IVirtualListProvider _dataProvider;
        private int _visibleItemCount;
        private int _topIndex;
        private int _itemHeight = DefaultItemHeight;
        private bool _showScrollBar = true;
        private VScrollBar _vScrollBar;
        private System.Windows.Forms.Timer _scrollTimer; // 明确指定Timer类型

        public VirtualListView()
        {
            // 基础设置
            SetStyle(ControlStyles.OptimizedDoubleBuffer |
                    ControlStyles.AllPaintingInWmPaint, true);
            View = View.Details;
            FullRowSelect = true;
            HeaderStyle = ColumnHeaderStyle.None;
            BorderStyle = BorderStyle.None;

            // 初始化滚动条
            _vScrollBar = new VScrollBar
            {
                Dock = DockStyle.Right,
                Width = SystemInformation.VerticalScrollBarWidth
            };
            _vScrollBar.Scroll += OnScroll;
            Controls.Add(_vScrollBar);

            // 明确使用Windows.Forms的Timer
            _scrollTimer = new System.Windows.Forms.Timer { Interval = 20 };
            _scrollTimer.Tick += OnScrollTimerTick;
        }

        #region 属性
        /// <summary>
        /// 数据提供器
        /// </summary>
        [Browsable(false)]
        public IVirtualListProvider DataProvider
        {
            get => _dataProvider;
            set
            {
                _dataProvider = value;
                UpdateScrollBar();
                Invalidate();
            }
        }

        /// <summary>
        /// 是否显示垂直滚动条
        /// </summary>
        [DefaultValue(true)]
        public bool ShowScrollBar
        {
            get => _showScrollBar;
            set
            {
                _showScrollBar = value;
                _vScrollBar.Visible = value;
                Invalidate();
            }
        }

        /// <summary>
        /// 列表项高度（像素）
        /// </summary>
        [DefaultValue(DefaultItemHeight)]
        public int ItemHeight
        {
            get => _itemHeight;
            set
            {
                _itemHeight = value;
                UpdateScrollBar();
                Invalidate();
            }
        }

        /// <summary>
        /// 当前可见区域的顶部索引
        /// </summary>
        [Browsable(false)]
        public int TopIndex
        {
            get => _topIndex;
            set
            {
                if (_dataProvider == null) return;

                value = Math.Max(0, Math.Min(value, _dataProvider.Count - _visibleItemCount));
                if (_topIndex != value)
                {
                    _topIndex = value;
                    _vScrollBar.Value = _topIndex;
                    Invalidate();
                }
            }
        }
        #endregion

        #region 核心方法
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            UpdateVisibleItemCount();
            UpdateScrollBar();
        }

        protected override void OnMouseWheel(MouseEventArgs e)
        {
            base.OnMouseWheel(e);
            TopIndex -= e.Delta > 0 ? 1 : -1;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (_dataProvider == null || _dataProvider.Count == 0)
            {
                base.OnPaint(e);
                return;
            }

            // 计算绘制区域
            var clipRect = e.ClipRectangle;
            int startY = clipRect.Top;
            int endY = clipRect.Bottom;
            int itemTop = 0;

            // 绘制可见项
            for (int i = 0; i < _visibleItemCount; i++)
            {
                int dataIndex = _topIndex + i;
                if (dataIndex >= _dataProvider.Count) break;

                var itemRect = new Rectangle(
                    0,
                    itemTop,
                    ClientSize.Width - (_showScrollBar ? _vScrollBar.Width : 0),
                    _itemHeight);

                if (itemRect.Bottom < startY)
                {
                    itemTop += _itemHeight;
                    continue;
                }
                if (itemRect.Top > endY) break;

                // 绘制项背景
                bool isSelected = SelectedIndices.Contains(dataIndex);
                using (var brush = new SolidBrush(isSelected ? SystemColors.Highlight : BackColor))
                {
                    e.Graphics.FillRectangle(brush, itemRect);
                }

                // 绘制项内容
                var item = _dataProvider.GetItem(dataIndex);
                TextRenderer.DrawText(
                    e.Graphics,
                    item.ToString(),
                    Font,
                    new Rectangle(itemRect.X + 2, itemRect.Y, itemRect.Width - 4, itemRect.Height),
                    isSelected ? SystemColors.HighlightText : ForeColor,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

                // 绘制分隔线
                using (var pen = new Pen(SystemColors.ControlDark))
                {
                    e.Graphics.DrawLine(pen,
                        itemRect.Left, itemRect.Bottom - 1,
                        itemRect.Right, itemRect.Bottom - 1);
                }

                itemTop += _itemHeight;
            }

            // 绘制空白区域
            if (itemTop < endY)
            {
                using (var brush = new SolidBrush(BackColor))
                {
                    e.Graphics.FillRectangle(brush,
                        0, itemTop,
                        ClientSize.Width,
                        ClientSize.Height - itemTop);
                }
            }
        }
        #endregion

        #region 私有方法
        private void UpdateVisibleItemCount()
        {
            _visibleItemCount = (int)Math.Ceiling((double)ClientSize.Height / _itemHeight);
        }

        private void UpdateScrollBar()
        {
            if (_dataProvider == null)
            {
                _vScrollBar.Enabled = false;
                return;
            }

            _vScrollBar.Minimum = 0;
            _vScrollBar.Maximum = Math.Max(0, _dataProvider.Count - 1);
            _vScrollBar.LargeChange = _visibleItemCount;
            _vScrollBar.Enabled = _dataProvider.Count > _visibleItemCount;
        }

        private void OnScroll(object sender, ScrollEventArgs e)
        {
            if (e.Type == ScrollEventType.EndScroll) return;
            TopIndex = e.NewValue;
        }

        private void OnScrollTimerTick(object sender, EventArgs e)
        {
            // 平滑滚动逻辑
            // 可根据需要实现惯性滚动效果
        }
        #endregion
    }

    /// <summary>
    /// 虚拟列表数据提供器接口
    /// </summary>
    public interface IVirtualListProvider
    {
        /// <summary>
        /// 获取列表项总数
        /// </summary>
        int Count { get; }

        /// <summary>
        /// 获取指定索引的列表项
        /// </summary>
        object GetItem(int index);
    }
}